#!/bin/bash

# FFmpeg本地视频分析播放器一键编译脚本
# 支持跨平台编译：Linux/macOS/Windows (通过WSL)

set -e  # 遇到错误立即退出

echo "🎬 FFmpeg本地视频分析播放器编译脚本"
echo "=================================="

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查系统
OS="$(uname -s)"
case "$OS" in
    Linux*)     PLATFORM=Linux;;
    Darwin*)    PLATFORM=Mac;;
    CYGWIN*|MINGW*|MSYS*) PLATFORM=Windows;;
    *)          PLATFORM="UNKNOWN:$OS";;
esac

echo -e "${GREEN}✅ 检测到系统: $PLATFORM${NC}"

# 检查必要工具
check_command() {
    if ! command -v "$1" &> /dev/null; then
        echo -e "${RED}❌ 错误: $1 未安装${NC}"
        exit 1
    fi
}

echo "🔍 检查编译依赖..."
check_command cmake
check_command make
check_command pkg-config

# 检查FFmpeg
if [ ! -d "ffmpeg-build" ]; then
    echo -e "${YELLOW}⚠️  未找到预编译的FFmpeg，请先准备ffmpeg-build目录${NC}"
    echo "请确保目录结构如下:"
    echo "  ffmpeg-build/"
    echo "  ├── include/ (FFmpeg头文件)"
    echo "  └── lib/     (FFmpeg库文件)"
    exit 1
fi

# 检查SDL2
if ! pkg-config --exists sdl2; then
    echo -e "${YELLOW}⚠️  未找到SDL2库${NC}"
    case "$PLATFORM" in
        Linux)
            echo "请安装SDL2开发包:"
            echo "  Ubuntu/Debian: sudo apt install libsdl2-dev"
            echo "  CentOS/RHEL:   sudo yum install SDL2-devel"
            echo "  Arch:          sudo pacman -S sdl2"
            ;;
        Mac)
            echo "请安装SDL2:"
            echo "  brew install sdl2"
            ;;
        Windows)
            echo "请通过MSYS2安装:"
            echo "  pacman -S mingw-w64-x86_64-SDL2"
            ;;
    esac
    exit 1
fi

# 创建构建目录
BUILD_DIR="build"
if [ -d "$BUILD_DIR" ]; then
    echo -e "${YELLOW}🧹 清理旧的构建目录...${NC}"
    rm -rf "$BUILD_DIR"
fi

mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

# 配置项目
echo -e "${GREEN}🔧 配置CMake项目...${NC}"
cmake ..

# 编译项目
echo -e "${GREEN}🔨 开始编译...${NC}"
make -j$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)

# 创建bin目录
mkdir -p ../bin

# 检查编译结果
if [ -f "video_info" ] && [ -f "frame_decoder" ] && [ -f "video_player" ]; then
    echo -e "${GREEN}✅ 编译成功！${NC}"
    echo "生成的可执行文件:"
    echo "  - video_info    : 查看视频信息"
    echo "  - frame_decoder : 逐帧解码器"
    echo "  - video_player  : 简易播放器"
    
    # 复制到bin目录
    cp video_info frame_decoder video_player ../bin/
    echo -e "${GREEN}📁 可执行文件已复制到 bin/ 目录${NC}"
else
    echo -e "${RED}❌ 编译失败，请检查错误信息${NC}"
    exit 1
fi

echo ""
echo "🎉 编译完成！使用方法："
echo "  1. 查看视频信息: ./bin/video_info test.mp4"
echo "  2. 逐帧解码:   ./bin/frame_decoder test.mp4"
echo "  3. 播放视频:   ./bin/video_player test.mp4"
